#ifndef __TRANSMIT_H__
#define __TRANSMIT_H__



#include "Marcos.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <cstring>
#include <unordered_set>

#include "Logger.h"

using namespace std;

// 平台特定的头文件和定义
#ifdef _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #pragma comment(lib, "ws2_32.lib")
    #define close closesocket
    #define socklen_t int
    #define usleep(x) Sleep((x)/1000)
#else
    #include <unistd.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
#endif

// 简化错误处理宏
#ifdef _WIN32
    #define ERROR_CHECK(ret, msg) { if((ret) == SOCKET_ERROR) { \
        std::cerr << msg << ": " << WSAGetLastError() << std::endl; \
        exit(EXIT_FAILURE); } }
#else
    #define ERROR_CHECK(ret, msg) { if((ret) < 0) { perror(msg); exit(EXIT_FAILURE); } }
#endif



class TcpSocket {
public:

#ifdef _WIN32
    using SocketType = SOCKET;
#else
    using SocketType = int;
#endif

    // TcpSocket(SocketType sockfd) 
    //     : sockfd_(sockfd), 
    //       running_(true){}
    TcpSocket() :running_(true),
    logger_(LogMan::instance())
    {
        logger_->trace("Clase TcpSocket construct succ~~ ");
    }
    virtual ~TcpSocket() 
    {
        running_ = false;

        #ifdef _WIN32
            shutdown(sockfd_server, SD_BOTH);
            closesocket(sockfd_server);
            closesocket(clientSocket);
        #else
            close(sockfd_);
        #endif

        recv_cv_.notify_all(); // 唤醒可能阻塞的Parse线程
        
        if (recv_thread_.joinable()) recv_thread_.join();
        if (send_thread_.joinable()) send_thread_.join();
        // if (listener_thread_.joinable()) listener_thread_.join();

        if (logger_) {
            logger_->flush(); // 显式刷新缓冲区
        }

    }

    void Start_Transmit()
    {
        std::packaged_task<void()> task_recv(std::bind(&TcpSocket::recv_loop, this));
        recv_thread_ = std::thread(std::move(task_recv));

        std::packaged_task<void()> task_send(std::bind(&TcpSocket::send_loop, this));
        send_thread_ = std::thread(std::move(task_send));
    }

    // 等待并获取数据（供Parse类调用）
    char* wait_and_fetch_data(int* len) 
    {
        std::unique_lock<std::mutex> lock(mutex_);
        recv_cv_.wait(lock, [this] { return new_data_available_ || !running_; });
        if (!running_) 
        {
            return NULL;
        }

        *len = data_size_;
        // memcpy(dest, recv_buffer_, data_size_);
        new_data_available_ = false;
        return recv_buffer_;
    }

    // 发送数据接口
    void send_data(const char* data, int len) 
    {
        {
            std::lock_guard<std::mutex> lock(send_mutex_);
            send_queue_.append(data, len);
        }
        send_cv_.notify_one();
    }

    //判断tcp socket是否建立连接
    bool Is_Socket_Connected() const
    {
        return (flag_rcv_is_startup && flag_snd_is_startup);
    }

    // 创建并连接socket的辅助函数
    SocketType create_and_listen_socket(int port);
    // 创建连接到服务器
    bool create_connect_to_server(int port);

private:
    void recv_loop() 
    {
        // char temp_buf[512];
        flag_rcv_is_startup = true;

        while (running_) 
        {
            
            int n = recv(clientSocket, recv_buffer_, sizeof(recv_buffer_), 0);
            int err = WSAGetLastError();
            if (n <= 0) 
            {
                running_ = false;
                recv_cv_.notify_all(); // 通知Parse线程退出
                break;
            }

            {
                std::lock_guard<std::mutex> lock(mutex_);
                // memcpy(recv_buffer_, temp_buf, n);
                data_size_ = n;
                new_data_available_ = true;
            }
            recv_cv_.notify_one(); // 通知Parse类有新数据
        }

        flag_rcv_is_startup = false;
    }

    void send_loop() 
    {
        int snd_cnt = 0;
        flag_snd_is_startup = true;

        while (running_) 
        {
            std::unique_lock<std::mutex> lock(send_mutex_);
            send_cv_.wait(lock, [this] { return !send_queue_.empty() || !running_; });

            if (!running_) break;

            snd_cnt = 0;

            while(send_queue_.size() != 0)
            {
                snd_cnt = send(clientSocket, send_queue_.data(), (int)send_queue_.size(), 0);
                #ifdef _WIN32
                    if (snd_cnt == SOCKET_ERROR) 
                    {
                        running_ = false;
                        break;
                    }
                #else
                    if (n <= 0) 
                    {
                        running_ = false;
                        break;
                    }
                #endif
                send_queue_.erase(0, snd_cnt); // 移除已发送数据
            }
            
        }

        flag_snd_is_startup = false;
    }

    void Listener_Loop();

    // 初始化Winsock (仅Windows需要)
    #ifdef _WIN32
    void init_winsock();
    #endif



    SocketType sockfd_server;
    std::atomic<bool> running_;

    // 接收相关
    static constexpr uint32_t SOCK_RCV_LEN = 1200;
    char recv_buffer_[SOCK_RCV_LEN];
    int data_size_ = 0;
    bool new_data_available_ = false;
    std::mutex mutex_;
    std::condition_variable recv_cv_;
    std::thread recv_thread_;

    // 发送相关
    std::string send_queue_; // 发送队列
    std::mutex send_mutex_;
    std::condition_variable send_cv_;
    std::thread send_thread_;

    //监听线程
    std::thread listener_thread_;
    std::mutex clientsMutex_;
    SOCKET clientSocket;
    SOCKET serverSocket;
    // std::unordered_set<SocketType> clients_;

    bool flag_rcv_is_startup = false;
    bool flag_snd_is_startup = false;

    std::shared_ptr<spdlog::logger> logger_;  // 日志器成员变量
};


#endif
